﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using StartupTaskRunner.Logging;
using System.Diagnostics.Contracts;

namespace StartupTaskRunner.Actions
{
    public class RunAction : ActionBase
    {
        public override string Type
        {
            get { return "Run"; }
        }        
        
        public override void Execute()
        {
            Logger.WriteMessage("Running a command");
            Logger.WriteMessage("\tExecuting commandFile: {0}", this.CommandFile);
            if (!string.IsNullOrWhiteSpace(this.CommandArguments))
            {
                Logger.WriteMessage("\twith command-line arguments: {0}", this.CommandArguments);
            } 
            Logger.WriteMessage("\tTimeout period: {0} ms", this.TimeOut.ToString());

            Process process = new Process();
            try
            {
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.RedirectStandardOutput = true;

                // TODO: check if file exists --> commands do not always refer to file e.g. notepad
                process.StartInfo.FileName = this.CommandFile;
                process.StartInfo.Arguments = this.CommandArguments;
                process.Start();

                if (!process.WaitForExit(this.TimeOut))
                {
                    process.Kill();
                    Logger.WriteMessage("Process killed. Execution took more than timeout period");
                }
                
                WriteReaderData("Standard Output",process.StandardOutput);
                WriteReaderData("Standard Error", process.StandardError);
            }
            catch (Exception e)
            {
                Logger.LogException(e);
            }
            finally
            {
                process.Close();
            }
        }

        private static void WriteReaderData(string header, StreamReader streamReader)
        {
            string data = streamReader.ReadToEnd();
            if (!string.IsNullOrWhiteSpace(data))
            {
                Logger.WriteMessage(header);
                Logger.WriteMessage(data);
            }
        }

        public string CommandFile { get; set; }

        public string CommandArguments { get; set; }

        public int TimeOut { get; set; }

    }
}
